<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Services\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SmsController extends ApiController
{
    public function smsBind(Request $request){
        $user_tel = $request['user_tel'];
        if (empty($user_tel)){
            return parent::ajaxReturn(201, new \stdClass(), '手机号不能为空');
        }

        //判断当前手机号吧是否是学员
        $res = User::queryTel($user_tel);
        if(!$res){
            return parent::ajaxReturn(201, new \stdClass(), '当前手机号不是学员');
        }
//
        if (Cache::has('start_time'.$user_tel)){
            $time = Cache::get('start_time'.$user_tel);
            if (time()-$time<60){
                $a = 60-(time()-$time);
                return parent::ajaxReturn(203,'剩余'.$a.'秒', '一分钟只能发送一次');
            }
        }

        /*次数限制*/
        $sendTimes = $this->counter('send_sms_counter_'.$user_tel);
        if($sendTimes > config('aliyunsms.sms_limit_times',10)){
            //throw new \Exception('短信验证码发送数量已超出当日最大限制，请明天再试');
            return parent::ajaxReturn(201, '短信验证码发送数量已超出当日最大限制', '信息提交成功');
        }

        if(!SmsService::sendSmsCode($user_tel)){
            return parent::ajaxReturn(201, new \stdClass(), '发送失败');
        }else{
            $this->counter('send_sms_counter_'.$user_tel,1);
            /*时间限制*/
            $time = time();
            $result = array(
                'code' => 0,
                'message' => '验证码发送成功!',
                'time' => time(),
                'data' => ""
            );
            Cache::put('start_time'.$user_tel,time(),1);
            return parent::ajaxReturn(200, $result, '信息提交成功');
        }
    }

}
